<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 引入组件 -->
      <page-tools :show-before="true">
        <!-- 左边的插槽 -->
        <template #before>
          <span>共{{ pagination.total }}条记录</span>
        </template>

        <!-- 右边的插槽 -->
        <template v-slot:after>
          <el-button type="warning" size="small" @click="$router.push('/import')">Excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">Excel导出</el-button>
          <el-button type="primary" size="small" class="el-icon-plus" @click="showDialog = true">&nbsp;&nbsp;新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格组件 -->
      <el-table
        v-loading="loading"
        style="width: 100%"
        :default-sort="{prop: 'date', order: 'descending'}"
        border
        :data="employeeLists"
      >
        <el-table-column
          type="index"
          label="序号"
          sortable
          width="100"
        />
        <el-table-column
          prop="username"
          label="姓名"
          sortable
          width="180"
        />
        <el-table-column
          prop="workNumber"
          label="工号"
          sortable
          width="180"
        />
        <el-table-column
          label="聘用形式"
          prop="formOfEmployment"
          :formatter="formatEmployment"
          sortable
          width="180"
        />
        <el-table-column
          label="部门"
          sortable
          width="180"
          prop="departmentName"
        />
        <el-table-column
          prop="timeOfEntry"
          label="入职时间"
          sortable
          width="180"
        >
          <template #default="{row}">
            <span>{{ row.timeOfEntry | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="enableState"
          label="账户状态"
          sortable
          width="180"
        >
          <template #default="{row}">
            <el-switch
              :model="row.enableState === 1"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          sortable
          width="280"
          fixed="right"
        >
          <template #default="{row}">
            <el-button type="text" size="small" @click="$router.push(`employee/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignRoles(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="removeEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-row type="flex" justify="center">
        <el-pagination
          :page-size="pagination.size"
          layout="total, prev, pager, next"
          :total="pagination.total"
          :current-page="pagination.page"
          @current-change="handleCurrentChange"
        />
      </el-row>

      <!-- 对话框组件 -->
      <add-employee :show-dialog.sync="showDialog" @updateEmployee="loadEmployeeLists" />
      <!-- 分配角色对话框 -->
      <assign-role ref="refAssign" :show-assign-role-dialog.sync="showAssignRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployLists, deleteEmployee } from '@/api/employee.js';
import EmployeeEnum from '@/api/constant/employees.js';
// 导入新增员工组件
import AddEmployee from './components/add_employee.vue';
import { formatDate } from '@/filters';
import AssignRole from '@/views/employees/components/assign-role.vue';
export default {
  components: {
    AddEmployee,
    AssignRole,
  },
  data() {
    return {
      employeeLists: [],
      // 分页数据
      pagination: {
        page: 1,
        size: 10,
        total: 0,
      },
      // 这个loading可以放到任何位置
      loading: false,
      // 控制对话框的显示和隐藏
      showDialog: false,
      // 控制分配角色对话框的显示和隐藏
      showAssignRoleDialog: false,
      // 用于给用户分配角色的useId
      userId: null,
    };
  },
  computed: {
    paramData() {
      return {
        page: 1,
        size: 10,
      };
    },
  },
  created() {
    this.loadEmployeeLists();
  },
  methods: {
    async loadEmployeeLists() {
      // 开启loading
      this.loading = true;
      const { total, rows } = await getEmployLists(this.paramData);
      this.employeeLists = rows;
      this.pagination.total = total;
      // console.log(this.employeeLists);
      // 关闭loading
      this.loading = false;
    },
    // 处理分页组件的页面变化
    handleCurrentChange(newPage) {
      this.paramData.page = newPage;
      this.loadEmployeeLists();
    },
    // 定义一个处理应聘格式的方法
    // cellValue是当前单元格的值
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find((item) => {
        if (item.id === cellValue) {
          return item;
        }
      });
      return obj ? obj.value : '未知';
    },
    // 删除员工
    async removeEmployee(id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await deleteEmployee(id);
        this.loadEmployeeLists();
        this.$message.success('您已经成功的删除了该项数据！');
      } catch (error) {
        console.log(error);
      }
    },
    // excel导出
    exportData() {
      //  做操作
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
      };
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployLists({ page: 1, size: this.pagination.total });
        const data = this.formatJson(headers, rows);

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
        });
        // 获取所有的数据
        // excel.export_json_to_excel({
        //   header: ['姓名', '薪资'],
        //   data: [['张三', 12000], ['李四', 5000]],
        //   filename: '员工薪资表',
        //   autoWidth: true,
        //   bookType: 'csv'
        // })
      });
    },
    // 定义一个处理excel导出数据data的方法
    formatJson(headers, rows) {
      // 首先遍历数组
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]);
          } else if (headers[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]]);
            return en ? en.value : '未知';
          }
          return item[headers[key]];
        });
      });
    },
    // 分配角色
    assignRoles(id) {
      this.userId = id;
      this.$refs.refAssign.getUserBaseInfo(id);
      this.showAssignRoleDialog = true;
    },
  },
};
</script>

<style>

</style>
